<template>
  <div class="app-container">
    <div class="search-bar">
      <el-form ref="queryFormRef" :model="queryParams" :inline="true">
        <el-form-item label="关键字" prop="keywords" v-if="false">
          <el-input
            v-model="queryParams.keywords"
            placeholder="字典名称/编码"
            clearable
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="search" @click="handleQuery()">搜索</el-button>
          <el-button icon="refresh" @click="handleResetQuery()" v-if="false">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-card shadow="never">
      <div class="mb-[10px] flex btnGroup">
        <el-button icon="ArrowLeft" @click="handleLastDir()"></el-button>
        <div class="prefix">
            {{ prefix.slice(0, prefixIndex).join("") }}
        </div>
        <el-button type="success" icon="plus" @click="handleAddDir()">新建文件夹</el-button>
        <el-button type="info" icon="Upload" @click="handleUpload()">上传文件</el-button>
        <el-button type="danger" icon="delete" @click="handleDeletes(ids)">批量删除</el-button>
      </div>

      <el-table
        v-loading="loading"
        :data="tableData"
        border
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="名称" prop="name">
            <template #default="{ row }">
                <a @click="handleEnterDir(row)" class="dirEl" v-if="row.isDir">{{ row.name.replace('/', '') }}</a>
                <span v-else>{{ row.name }}</span>
            </template>
        </el-table-column>
        <el-table-column label="上传时间" prop="lastModified">
            <template #default="{ row }">
                {{ row.lastModified ? formatDate(row.lastModified) : '--' }}
            </template>
        </el-table-column>
        <el-table-column label="类型" prop="isDir">
            <template #default="{ row }">
                {{ row.isDir ? '文件夹' : '文件' }}
            </template>
        </el-table-column>
        <el-table-column label="大小" prop="size">
            <template #default="{ row }">
                {{ row.size ? row.size + 'B' : '--' }}
            </template>
        </el-table-column>
        <el-table-column label="操作">
          <template #default="scope">
            <div v-if="!scope.row.isDir">
                <el-button type="text" @click="handleDel(scope.row)">删除</el-button>
                <el-button type="text" @click="handleDownload(scope.row)">下载</el-button>
            </div>
            <div v-else>--</div>
          </template>
        </el-table-column>
      </el-table>

      <div class="botBtnGroup">
        <el-button @click="nextPage" size="small" v-show="isTruncated">下一页</el-button>
      </div>
    </el-card>


    <el-dialog
        v-model="dialogVisible"
        title="上传文件"
        width="500"
    >
        <div>
            <el-upload
                v-if="dialogVisible"
                class="upload-demo"
                :auto-upload="false"
                :on-change="handleChangeUpload"
                drag
                action=""
                multiple
            >
                <el-icon class="el-icon--upload"><upload-filled /></el-icon>
                <div class="el-upload__text">
                    请将需要上传的文件/文件夹拖到此处
                </div>
            </el-upload>

        </div>
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="setDialogVisible(false)">取消</el-button>
                <el-button type="primary" @click="handleUploadAction">确定</el-button>
            </div>
        </template>
    </el-dialog>
  </div>
</template>


<script setup>
import { fileInfoUpload } from '@/utils/formRequest'
import { getListApi, remove, download } from '@/api/oss/index.js'
import useToggle from "@/hooks/useToggle";

const [loading, _, setLoading] = useToggle();
const [dialogVisible, , setDialogVisible] = useToggle();

const paging = ref({
  size: 10,
  page: 1,
  total: 0,
})

const ids = ref([])
const tableData = ref([])
const queryParams = ref({
  keywords: ''
})
const handleQuery = () => {
    getList()
}
const handleResetQuery = () => {}
const handleSelectionChange = (e) => {
    ids.value = e.map(item => {
        return prefix.value.slice(0, prefixIndex.value).join("") + item.name
    })
}
const handleAddClick = () => {}
const handleDelete = () => {}

const isTruncated = ref(false) // 是否存在下一页
const nextStartAfter = ref("")
const prefix = ref([])
const prefixIndex = ref(0)
const getList = async (startAfter = "") => {
    ids.value = []
    setLoading(true)
    const res = await getListApi({
        prefix: prefix.value.slice(0, prefixIndex.value).join(""),
        size: paging.value.size,
        startAfter,
    }).finally(() => {
        setLoading(false)
    })
    isTruncated.value = res.isTruncated
    nextStartAfter.value = res.nextStartAfter
    tableData.value = res.items
    console.log(res)
}

const fileList = ref([])
const handleChangeUpload = (e, list) => {
    fileList.value = list
}

const handleUploadAction = () => {
    for(let i = 0; i <= fileList.value.length; i++) {
        const item = fileList.value[i]
        console.log(item)
        if(item) {
            const filename = item.name
            const path = prefix.value.slice(0, prefixIndex.value).join("")
            const params = `?filename=${filename}&path=${path}`
            const fileData = new FormData()
            fileData.append('file', item.raw)
            fileInfoUpload(`/oss/upload${params}`, fileData).then(res => {
                setLoading(false)
                setDialogVisible(false)
                getList()
            }).finally(() => {
                setLoading(false)
                handleClose(false)
            })
        }
    }
}

const handleUpload = () => {
    setDialogVisible(true)
}

const handleAddDir = () => {
    ElMessageBox.prompt('请输入文件夹名称', '新建文件夹', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
    }).then(({ value }) => {
        if(!value) return ElMessage({
            message: '请输入文件名',
            type: 'warning',
            plain: true,
        })
        tableData.value.push({ name: value + '/', isDir: true })
    })
}

const handleDeletes = (ids) => {
    ElMessageBox.confirm(
        '是否确定删除选中的文件',
        '温馨提示',
        {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        }
    )
        .then(() => {
            remove({
                paths: ids
            }).then(res => {
                getList()
            })
        })
}

const handleDel = (row) => {
    ElMessageBox.confirm(
        '是否确定删除该文件',
        '温馨提示',
        {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        }
    )
        .then(() => {
            remove({
                paths: [prefix.value.slice(0, prefixIndex.value).join("") + row.name]
            }).then(res => {
                getList()
            })
        })
}

const handleDownload = (row) => {
    download({
        path: prefix.value.slice(0, prefixIndex.value).join("") + row.name
    }, { responseType: 'blob' }).then(res => {
        console.log(res)

        const fileStr = res.headers["content-disposition"] && res.headers["content-disposition"].split("=")[1];
        const fileName = decodeURIComponent(fileStr?.split("''")[1])

        // 创建Blob对象
        const blob = new Blob([res.data], { type: res.headers['content-type'] });
        
        // 创建下载链接
        const url = window.URL.createObjectURL(blob);
        const link = document.createElement('a');
        
        // 设置属性
        link.href = url;
        link.download = fileName || 'download';
        link.style.display = 'none';
        
        // 添加到DOM
        document.body.appendChild(link);
        
        // 触发点击
        link.click();
        
        // 清理
        document.body.removeChild(link);
        window.URL.revokeObjectURL(url);
    })
}

const handleEnterDir = (e) => {
    if(!e.isDir) return
    console.log(e,'双击行')
    prefix.value.push(e.name)
    prefixIndex.value++

    console.log(prefix.value)
    getList()
}

const handleLastDir = () => {
    if(prefixIndex.value > 0) {
        prefixIndex.value--
        prefix.value.pop()
        getList()
    }
}
const handleNextDir = () => {
    if(prefixIndex.value <= prefix.length) {
        prefixIndex.value++
        getList()
    }
}

const nextPage = () => {
    if(isTruncated.value) {
        getList(nextStartAfter.value)
    }
}

// 格式化日期
const formatDate = (date) => {
    const d = new Date(date)
    return d.toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit',
        hour12: false
    }).replace(/-/g, '-')
}

getList()
</script>

<style scoped lang="scss">
.pagination{
  display: flex;
  justify-content: flex-end;
  margin-top: 15px;
}
.btnGroup{
    display: flex;
    align-items: center;
}
.prefix{
    margin: 0 5px;
}
.botBtnGroup{
    display: flex;
    justify-content: flex-end;
    margin-top: 10px;
}

.dirEl:hover {
    text-decoration: underline;
}
</style>
